package com.dayaokeji.rhythmschoolstudent.client.common.base.common;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.bumptech.glide.RequestManager;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.callback.SharedElementCallback2;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.event.AppStateEvent;
import com.dayaokeji.rhythmschoolstudent.glide.GlideUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DensityUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BaseActivity extends AppCompatActivity {

    private final SharedElementCallback2 sharedElementCallback2 = new SharedElementCallback2(){};
    private Unbinder unbinder;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusIconDark(true);
        setStatusBarDarkMode(true, this);
        // 取消转场快照，防止OOM
        setEnterSharedElementCallback(sharedElementCallback2);
        setExitSharedElementCallback(sharedElementCallback2);
        ActivityStackManager.add(this);
        DensityUtil.setDefault(this);
        setStatusBarDarkIcon(getWindow(), true);
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        unbinder = ButterKnife.bind(this);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        unbinder = ButterKnife.bind(this);
    }

    protected void addDisposable(@NonNull Disposable d) {
        compositeDisposable.add(d);
    }


    @Override
    protected void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();
            unbinder = null;
        }
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
        super.onDestroy();
    }


    /**
     * 设置system status bar 透明
     * @param enabled
     */
    public void setTranslucentStatusEnabled(boolean enabled) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            View decorView = window.getDecorView();
            int flags = decorView.getSystemUiVisibility();
            int layoutFullMask = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            flags = enabled ? flags | layoutFullMask : flags & ~layoutFullMask;
            decorView.setSystemUiVisibility(flags);
            window.setStatusBarColor(enabled ? Color.TRANSPARENT : getResources().getColor(R.color.colorPrimary));
       }
    }

    public void setStatusIconDark(boolean isDark) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = getWindow().getDecorView();
            int flags = decorView.getSystemUiVisibility();
            flags = isDark ? flags | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR : flags & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            decorView.setSystemUiVisibility(flags);
        }
    }

    public void setStatusBarDarkMode(boolean darkMode, Activity activity) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            @SuppressLint("PrivateApi") Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkMode ? darkModeFlag : 0, darkModeFlag);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setStatusBarDarkIcon(Window window, boolean dark) {
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
            } catch (Exception e) {
                Logger.e("setStatusBarDarkIcon: failed");
            }
        }
    }


    @Override
    public boolean onSupportNavigateUp() {
        if (!super.onSupportNavigateUp()) {
            supportFinishAfterTransition();
        }
        return true;
    }

    protected RequestManager withGlide() {
        return GlideUtils.with(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().post(new AppStateEvent(true, Constant.APP_STATE_FOREGROUND_CODE));
    }

}
